package five_Net.shangchuan;

import java.io.*;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket s;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        int count = 0;
        File file = new File("mian\\src\\five_Net\\shangchuan\\copy[" + count + "].txt");
        while (file.exists()) {
            count++;
            file = new File("mian\\src\\five_Net\\shangchuan\\copy[" + count + "].txt");
        }
        BufferedReader br = null;
        BufferedWriter bw = null;
        BufferedWriter bwServer = null;
        try {
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            bwServer.write("[" + count + "]Copy Over!!!");
            bwServer.newLine();
            bwServer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bwServer != null) {
                try {
                    bwServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
